#!/usr/bin/env bash
JVMFLAGS=Dfile.encoding=UTF-8
APPNAME=authrization-manager
APP_HOME="${BASH_SOURCE-$0}"
APP_HOME="$(dirname "${APP_HOME}")"
APP_HOM="$(pwd "${APP_HOME}")"
if [ "$JAVA_HOME" != "" ]; then
    JAVA="$JAVA_HOME/bin/java"
else
  JAVA=java
fi
mkdir -p $APP_HOME/../logs
mkdir -p $APP_HOME/../pid

for i in  "$APP_HOME"/../lib/*.jar
do
   CLASSPATH="$i:$CLASSPATH"
done

CONF_HOME="${APP_HOME}/../."
CONF_HOME="$(cd "$(dirname "${CONF_HOME}")"; pwd)"
CONF_HOME="${CONF_HOME}/conf"

CLASSPATH="$CONF_HOME:$CLASSPATH"

DAEMON_OUT="$APP_HOME/../logs/sdt.out"
MAIN_CLASS="com.ytraveler.AuthrizationManagerApplication"
PID_FILE="$APP_HOME/../pid/app.pid"

echo "Starting $APP_NAME ... "
if [ -f "$PID_FILE" ]; then
  if kill -0 `cat "$PID_FILE"` > /dev/null 2>&1; then
     echo $command already running as process `cat "$PID_FILE"`.
     exit 0
  fi
fi

JAVA_MEM_OPTS=""
    BITS=`java -version 2>&1 | grep -i 64-bit`
    if [ -n "$BITS" ]; then
        JAVA_MEM_OPTS="-server -Xms512m -Xmx1024m -Xmn512m -XX:SurvivorRatio=2 -XX:PermSize=96m -XX:MaxPermSize=256m -Xss256k -XX:-UseAdaptiveSizePolicy -XX:MaxTenuringThreshold=15 -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError"
    else
        JAVA_MEM_OPTS="-server -Xms512m -Xmx512m -XX:NewSize=256m -XX:MaxNewSize=256m -XX:MaxPermSize=128m "
    fi

nohup "$JAVA" -D$APP_NAME $JAVA_MEM_OPTS -cp "$CLASSPATH" $JVMFLAGS $MAIN_CLASS >/dev/null 2>&1 &

if [ $? -eq 0 ]
then
  if /bin/echo -n $! > "$PID_FILE"
  then
    sleep 1
    echo "$APP_NAME started"
  else
    echo "failed to start $APP_NAME"
    exit 1
  fi
else
  echo "failed to start $APP_NAME"
  exit 1
fi
